Subject: Re: Can somebody explain me how to do this in C++
Date: Fri, 08 Mar 1996 15:27:35 -0500
Organization: AT&T New Media Services
Message-ID: <31409837.4AB2@staff.ichange.com>
References: <4hkb2o$ko3@mo6.rc.tudelft.nl>
NNTP-Posting-Host: 198.112.128.210
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-Mailer: Mozilla 2.0 (Win95; I)
Ejo Schrama wrote:
>
> Suppose you've got a base class containing protected data and several
> public methods among which there are some virtual ones. ...during the execution of a program...you only want to deal with a linked list of base class objects...There are
> local variables declared as protected data inside the inhereted subclasses
> (which don't exist in the baseclass) and I want to access those variables
> in the while construction described above.
This is a well known design flaw not a language limitation. There are many ways out of it, but first you have to undertsand
the flaw. Let's say you have a linked list of animals. You want to treat them as animals, rather than as birds, horses and
fish. However, from time to time, you want to tell a fish to swim and a bird to fly.
You have a number of choices. You can move a virtual function into the base class (e.g., Animal::move()) and then override
it appropriately in each derived class. That's fine if all animals can reasonably be expected to move(). This works, but
brings the risk that functions all percolate up into the base class. In general, you want to percolate shared functionality
up the hierarchy, without migrating the interface of each class into the base.
In any case, what do you do if there are methods which don't belong in every derived class?
Again, a few options. You can have a method makeAHome() which makes a nest in a bird, digs a hole in a mouse and does nothing
in a horse object, but feh. A second option is to "cast down" to the derived class. That is, in your loop you can ask each
object if it is a bird, and if it is you can cast it to a bird and then call bird-only methods. This is usually a sign of
very poor design, but sometimes it is the only way to get it done.
These issues often come up with regard to collection classes, which is where templates can help a lot. Other issues arise
because of single inheritance. Here multiple inheritance and delegation can often solve the problem.
Now, you also added a red herring with the "protected data" issue. I'm not convinced it ever makes sense to have protected
data (protected methods, absolutely, but not member data). The right answer is to make the data PRIVATE. Then, if you need
access, use public or virtual & protected access methods.
Hope that helps, if not give a holler. -j
--
Jesse Liberty. (AT&T New Media Services) jl@staff.ichange.com